package ntd.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * 本地计算机操作
 */
public class UtilLocal {
    public static void main(String[] args) {
        // 123.161.201.200
        System.out.println("本机IP:" + getWebIp());
    }

    /**
     * 获取本机ip
     *
     * @return
     */
    public static String getIpAddress() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                } else {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress ip = addresses.nextElement();
                        if (ip != null && ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("IP地址获取失败" + e.toString());
        }
        return "";
    }

    /**
     * 获取公网ip
     * 官网：https://www.ip138.com/
     *
     * @return
     */
    public static String getWebIp() {
        String strUrl = "https://api.ip138.com/ipv4/?token=ddf5f7f152562f0841c9d3e4a151590d";
        final String str = HttpUtil.get(strUrl);
        return JSONUtil.parseObj(str).getStr("ip");
    }
}
